import React, { useEffect, useState } from 'react';
import smartfetch from '@mmstudio/an000058';
import { IData, Query as Q1, Result as R1 } from '../../api/admin/dictsys/query.api';
import api from '../../../atoms/api';
import Pagination from '../../../components/pagination';
import RightContainer from '../../../components/rightcontainer';
import Search from '../../../components/search';
import Title from './title';
import List from './list';
import Add from './add';

export default function Content({ initquery }: {
	initquery: Q1;
}) {
	// 查询服务
	const [data, setdata] = useState<R1>({
		count: 0,
		data: []
	});
	const [query, setquery] = useState<Q1>(initquery);
	async function reload(q: Q1) {
		setquery(q);
		const data = await smartfetch<R1, Q1>(api['/api/admin/dictsys/query'], 'get', q);
		setdata(data);
	}
	useEffect(() => {
		void reload(query);
	}, []);
	return <>
		{/* 标题 */}
		<Title />
		{/* 搜索框+新增 */}
		<RightContainer>
			<Search<IData>
				pagesize={Number(query.pagesize)}
				service={api['/api/admin/dictsys/query']}
				initq={query.q}
				label='请输入名称或值'
				onChange={(v) => {
					setdata({
						count: v.count,
						data: v.data
					});
					setquery({
						q: v.q,
						page: v.page.toString(),
						pagesize: query.pagesize
					});
				}} />
			<Add />
		</RightContainer>
		{/* 列表 */}
		<List data={data.data} />
		{/* 分页 */}
		<RightContainer>
			<Pagination
				current={Number(query.page || '1')}
				pageSize={Number(query.pagesize || '10')}
				showTitle
				total={data.count}
				onChange={(p, s) => {
					const q = {
						q: query.q,
						page: p.toString(),
						pagesize: s.toString()
					} as Q1;
					setquery(q);
					reload(q);
				}}
			/>
		</RightContainer>
	</>;
}
